package com.ymh.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

/**
 * @author: 13590
 * @date: 2020/11/6 15:59
 * @description:
 */
@Primary
@Component
public class GatewaySwaggerResourceProvider implements SwaggerResourcesProvider {

  private static final String OAS_30_URL = "/v3/api-docs";

  /**
   * 网关路由
   */
  @Autowired
  private RouteLocator routeLocator;

  @Autowired
  private GatewayProperties gatewayProperties;
  /**
   * 网关应用名称
   */
  @Value("${spring.application.name}")
  private String self;

  @Override
  public List<SwaggerResource> get() {
    List<RouteDefinition> ds = gatewayProperties.getRoutes();
    List<SwaggerResource> resources = new ArrayList<>();
    List<String> routeHosts = new ArrayList<>();
    // 获取所有可用的host：serviceId
    routeLocator.getRoutes()
        .filter(route -> route.getUri().getHost() != null)
        .filter(route -> StringUtils.equals(route.getUri().getScheme(), "lb"))
        .subscribe(route -> routeHosts.add(route.getUri().getHost()));
    Set<String> dealed = new HashSet<>();
    ds.forEach(routeDefinition -> {
      // 拼接url
      String url = "/" + routeDefinition.getId() + OAS_30_URL;
      if (!dealed.contains(url)) {
        dealed.add(url);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setUrl(url);
        swaggerResource.setName(routeDefinition.getId());
        swaggerResource.setSwaggerVersion("3.0.3");
        resources.add(swaggerResource);
      }
    });
    return resources;
  }
}
